package com.whz.governance.http.ribbon.mvc;

import com.whz.governance.http.ribbon.Constants;
import com.whz.governance.http.ribbon.context.RibbonFilterContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * webapp 保存灰度测试header到ribbon上下文
 *
 * @author whz
 */
@Slf4j
public class HttpGreyTagFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest,
                                    HttpServletResponse httpServletResponse,
                                    FilterChain filterChain)
            throws ServletException, IOException {
        String greyTag = GreyFlagUtils.getFlag(httpServletRequest);
        if (!StringUtils.isEmpty(greyTag)) {
            log.info("header`s grey-flag is [{}]", greyTag);
            // 开启ribbon的灰度开关（线程级别）
            RibbonFilterContextHolder.getCurrentContext().add(Constants.GREY_FLAG, greyTag);
        } else {
            RibbonFilterContextHolder.getCurrentContext().remove(Constants.GREY_FLAG);
        }
        filterChain.doFilter(httpServletRequest, httpServletResponse);
    }
}